﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.Extensions
{
    /// <summary>
    /// 缩略图
    /// </summary>
    public static class ThumbnailExtenisons
    {
        /// <summary>
        /// 创建缩略图
        /// 如宽度高度不为0，则使用指定高度
        /// 如果高度为0，则按宽度计算高度
        /// 如果宽度为0，则按高度计算宽度
        /// </summary>
        /// <param name="img">图片</param>
        /// <param name="width">高度</param>
        /// <param name="height">宽度</param>
        /// <returns></returns>
        public static Bitmap CreateThumbnail(this Bitmap img, int width, int height = 0)
        {
            if (width == 0 && height == 0)
            {
                throw new ArgumentNullException("缩略图宽带高度不能都为0");
            }

            if (height == 0)
            {
                height = (int)(img.Height / ((double)img.Width / width));
            }
            if (width == 0)
            {
                width = (int)(img.Width / ((double)img.Height / height));
            }

            var newWidth = img.Width > width ? width : img.Width;
            var newHeight = img.Height > height ? height : img.Height;

            return new Bitmap(img, new Size(newWidth, newHeight));
        }
    }
}
